<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script src="./js/03-ajax.js"></script>
  <script>
    const p1 = new Promise((resolve, reject) => {
      setTimeout(() => {
        reject("fail")
        // resolve("第一个异步")
      }, 1000)
    }).catch(error => {
      console.log(error)
    })
    const p2 = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("第二个异步")
      }, 1000)
    })

    Promise.all([p1, p2]).then(result => {
      console.log(result) // 没有错误["第一个异步", "第二个异步"]；如果p1有错误接收，那么默认fulfilled状态返回，[undefined, "第二个异步"]
    }).catch(error => {
      console.log(error) // 有错误 fail 
    })

    // 根据用户批量获取用户资料
    // const promises = ['p1', 'p2'].map(name => {
    //   return ajax('http://localhost:3000/posts')
    // })

    // Promise.all(promises).then(users => {
    //   console.log(users)
    // }).catch(error => {
    //   console.log(error)
    // })
    // 封装
    function getUsers(names) {
      let promises = names.map(name => {
        return ajax('http://localhost:3000/posts')
      })
      return Promise.all(promises)
    }
    getUsers(['p1', 'p2']).then(users => {
      console.log(users)
    }).catch(error => {
      console.log(error)
    })
  </script>
</body>
</html>